﻿using Fast.UnifyResult.Internal;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Fast.Middlewares
{
    public class GlobalExceptionMiddleware
    {
        private readonly RequestDelegate _next;

        public GlobalExceptionMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context); // 执行请求
            }
            catch (Exception ex)
            {
                // 如果出现异常，处理并返回统一格式的错误信息
                await HandleExceptionAsync(context, ex);
            }
        }

        private Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            var response = context.Response;
            response.ContentType = "application/json";

            // 可以根据异常类型设置不同的状态码
            var statusCode = exception switch
            {
                ArgumentException => StatusCodes.Status400BadRequest,
                InvalidOperationException => StatusCodes.Status500InternalServerError,
                _ => StatusCodes.Status500InternalServerError
            };

            // 创建统一格式的错误返回
            var result = new RESTfulResult<object>
            {
                StatusCode = statusCode,
                Succeeded = false,
                Errors = new[] { exception.Message },
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
            };

            response.StatusCode = statusCode;
            return response.WriteAsJsonAsync(result);
        }
    }
}
